package edu.bbu.license.client.android.services.transfer;

import android.content.Intent;
import edu.bbu.license.client.android.application.MainApplication;
import edu.bbu.license.client.android.services.BaseService;
import edu.bbu.license.client.android.services.BaseServiceProvider;
import edu.bbu.license.client.android.services.transfer.worker.SimpleTransferService;
import edu.bbu.license.client.android.services.transfer.worker.TransferService;

public class TransferServiceProvider extends BaseServiceProvider {

	private static TransferService transferService = new SimpleTransferService(); 
	private static boolean syncStarted = false;
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if(!syncStarted) {
			syncStarted = true;
			startAutoSync();
		}
		
		return START_STICKY;
	}
	
	public TransferService getTransferService() {
		startService();
		return transferService;
	}
	
	@Override
	protected void startService() {
		MainApplication mainApplication = MainApplication.getInstance();
		mainApplication.startService(new Intent(mainApplication, TransferServiceProvider.class));		
	}

	private void startAutoSync() {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				BaseService baseService = (BaseService) transferService;
				
				try {
					while(true) {
						if(baseService.isAutoSyncEnabled()) {
							transferService.startSynchronization();
						}
						
						Thread.sleep(30000);
					}
				} catch (Exception e) { }
			}
		}).start();
	}
}
